#include "Texture.h"
#include "stb_image.h"
using namespace std;
SakuraAge::Texture::Texture(string path, TextureMode mode)
{
	int width, height, nrChannels;
	unsigned char* data = nullptr;
	data = stbi_load(path.c_str(), &width, &height, &nrChannels, 0);
	glGenTextures(1, &textureID);
	glBindTexture(GL_TEXTURE_2D,textureID);

	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, (GLint)mode.surroundMod);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, (GLint)mode.surroundMod);
	if (mode.surroundMod == SurroundMod::ClampToColor)
	{
		if (mode.color == nullptr)
		{
			mode.color = new float[3];
			mode.color[0] = 0;
			mode.color[1] = 1;
			mode.color[2] = 1;
			mode.deleteColor = true;
		}
		glTexParameterfv(GL_TEXTURE_2D, GL_TEXTURE_BORDER_COLOR, mode.color);
		if (mode.deleteColor)
		{
			delete[] mode.color;
		}
	}
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, (GLint)mode.resolution);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, (GLint)mode.resolution);
	if (data) {
		glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, data);
		glGenerateMipmap(GL_TEXTURE_2D);
	}
	m_size.x = (float)width;
	m_size.y = (float)height;
	stbi_image_free(data);
}

void SakuraAge::Texture::ReloadTexture(string path, TextureMode mode)
{
	glDeleteTextures(1, &textureID);
	int width, height, nrChannels;
	unsigned char* data = stbi_load(path.c_str(), &width, &height, &nrChannels, 0);

	glGenTextures(1, &textureID);
	glBindTexture(GL_TEXTURE_2D, textureID);

	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, (GLint)mode.surroundMod);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, (GLint)mode.surroundMod);
	if (mode.surroundMod == SurroundMod::ClampToColor)
	{
		if (mode.color == nullptr)
		{
			mode.color = new float[3];
			mode.color[0] = 0;
			mode.color[1] = 1;
			mode.color[2] = 1;
			mode.deleteColor = true;
		}
		glTexParameterfv(GL_TEXTURE_2D, GL_TEXTURE_BORDER_COLOR, mode.color);
		if (mode.deleteColor)
		{
			delete[] mode.color;
		}
	}
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, (GLint)mode.resolution);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, (GLint)mode.resolution);

	glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, data);
	glGenerateMipmap(GL_TEXTURE_2D);

	stbi_image_free(data);
}

void SakuraAge::Texture::Bind()
{
	glActiveTexture(GL_TEXTURE0);
	glBindTexture(GL_TEXTURE_2D, textureID);
}

SakuraAge::Texture::~Texture()
{
	glDeleteTextures(1, &textureID);
}

SakuraAge::Texture::TextureMode::TextureMode(SurroundMod sur, Resolution res, float* color, bool deleteColor)
{
    surroundMod = sur;
	resolution = res;
	this->color = color;
	this->deleteColor = deleteColor;
}
